import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { message } from 'antd';
import {
  queryBookingCourierList,
  deleteCourier,
  outUserList,
  operAddOutUser,
} from './service';
import { fetchValidation } from '@/utils';

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    fetch: Effect;
    fetchOutUserList: Effect;
    addOutUser: Effect;
    delete: Effect;
  };
  reducers: {
    save: Reducer;
    saveOutUser: Reducer;
  };
}

const stateInfo = {
  dataInfo: {
    list: [],
    count: 0,
  },
  courierInfo: {
    list: [],
    count: 0,
  },
};

const Model: ModelType = {
  namespace: 'bookingCourierList',

  state: stateInfo,

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(queryBookingCourierList, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'save',
        payload: response.body,
      });
    },

    * fetchOutUserList({ payload }, { call, put }) {
      const response = yield call(outUserList, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'saveOutUser',
        payload: response.body,
      });
    },

    * addOutUser({ payload }, { call, put }) {
      const response = yield call(operAddOutUser, payload);
      const data = fetchValidation(response);
      if (data) {
        message.success('添加成功');
        yield put({
          type: 'fetch',
          payload: { cabinetId: payload.cabinetId },
        });
      }
    },

    * delete({ payload: { id, ...query } }, { call, put }) {
      const response = yield call(deleteCourier, { id });
      const data = fetchValidation(response);
      if (data) {
        message.success('删除成功');
        yield data && put({ type: 'fetch', payload: query });
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        dataInfo: action.payload,
      };
    },

    saveOutUser(state, action) {
      return {
        ...state,
        courierInfo: action.payload,
      };
    },
  },
};

export default Model;
